package Welsy4.Connect.commands
{
	import com.adobe.cairngorm.commands.SequenceCommand;
	import mx.rpc.events.ResultEvent;
	import Welsy4.Connect.business.AuthenticationDelegate;
	import Welsy4.Connect.events.AuthenticationEvent;
	import Welsy4.Connect.events.ChainEvent;
	import Welsy4.Connect.events.ResponseEvent;
	import Welsy4.Connect.model.ConnectModel;
	import Welsy4.Connect.vo.HttpServiceHandler;
	
	import com.adobe.cairngorm.commands.Command;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;

	public class LoginCommand extends SequenceCommand implements Command, IResponder
	{
		public function LoginCommand()
		{
		}

		override public function execute(event:CairngormEvent):void
		{
			ConnectModel.getInstance().addQueue("LoginCommand.execute/nlogin : "+ ChainEvent(event).eventRequest.login);
			this.nextEvent = ChainEvent(event).nextChainedEvent;
			
			//il controller esegue questo metodo quando intercetta l'evento 
			var delegate : AuthenticationDelegate = new AuthenticationDelegate(this);
			var le : AuthenticationEvent = AuthenticationEvent(event);
			delegate.Login(ChainEvent(event).eventRequest.login);
			
			
		}
		
		public function result(event : Object):void
		{
			// response XML
			ConnectModel.getInstance().addQueue("LoginCommand.result");
			
			ConnectModel.getInstance().isLogged = true;
			ConnectModel.getInstance().httpServiceHandler = new HttpServiceHandler();
			ConnectModel.getInstance().httpServiceHandler.setXML(event.result);
			
			// verify status response
			if (ConnectModel.getInstance().httpServiceHandler.getResultStatus() == ConnectModel.SESSION_OK) {
				CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.USER_LOGGED_IN, true, ResponseEvent.OK, event.result));
				
				this.executeNextCommand();
			} else {
			    CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR, false, ResponseEvent.INVALID, event.result));
				// break: some error occurs in logging in
				Alert.show(ConnectModel.getInstance().httpServiceHandler.getResultStatus() + " " + ConnectModel.getInstance().httpServiceHandler.getResultStatusInfo() );
			}
			
			
			
		    
			
		}
		
		public function fault(event : Object):void
		{
			CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR, false, ResponseEvent.LOGIN_COMMAND_FAULT, event));
			ConnectModel.getInstance().addQueue("LoginCommand.fault");
		}
		
	}
}